<?php

namespace App\Common;

use App\Constants\ErrorCode;
use think\config\driver\Json;

trait Res
{

    /**
     * 成功返回
     * @param string $message
     * @param null $data
     * @return array
     */
    public static function Success(string $message = '请求成功', $data = null): array
    {
        if (empty($data)) {
            return ['code' => ErrorCode::SUCCESS, 'message' => $message];
        }
        return ['code' => ErrorCode::SUCCESS, 'message' => $message, 'data' => $data];
    }

    /**
     * 失败返回
     * @param int $code
     * @param string $message
     * @return array
     */
    public static function Error(int $code, string $message): array
    {
        return ['code' => $code, 'message' => $message];
    }

    /**
     * 输出json格式
     * @param null $data
     * @return string
     */
    public static function JsonSuccess($data = null): string
    {
        return json_encode($data);
    }

    /**
     * 输出json错误格式
     * @param string $message
     * @return string
     */
    public static function JsonError(string $message): string
    {
        return json_encode(['status' => ErrorCode::ERROR, 'msg' => $message]);
    }

}